<template>
	<view :style="viewColor">
		<view class="bus-index">
			<view class="navbar" :style="{ height: navH + 'rpx', opacity: opacity }">
				<view class="navbar-title" :style="'height:' + navH + 'rpx;'">
					<view class="display-flex display-flex-align-center" :style="'margin-top:'+(sysHeight+20)+ 'rpx;'">景区直通车</view>
				</view>
			</view>
			<!-- #ifndef MP-ALIPAY -->
			
			<view class="head-wrapper" id="home" :style="{ top: homeTop + 'rpx' }">
				<view class="head-menu-new" :style="{color: (opacity > 0.7 ?'#000' :'#fff'),background:  (opacity > 0.7 ?'#fff' :'rgba(0, 0, 0, .25)'),border: (opacity>0.7?'none':'')}">
					<view class='iconfont icon-ic_left' @click="returns"></view>
				</view>
			</view>
			<!-- #endif -->
			<view class="ova w100">
				<view class="w100">
					<view class="">
						
					</view>
					<view class="bus-index-bg">
						<image src="https://qiniu.gzyxly.cn/def/49a10202411060030467971.jpg" class="w100 h100">
					</view>
					<view class="bus-index-search">
						<view class="pd-tb10 relative">
							<text class="bus-from">出发城市/景点</text>
							<text class="bus-to">到达城市/景点</text>
							<view class="bus-index-city">
								<view @click="goStartCityList('bus')" class="bus-station station-left text-black"  :class="changeFlag?'swap-animation':''">
									<text :class="start_loc?'':'text-cf'">{{start_loc?start_loc.name:'选择出发地'}}</text>
								</view>
								<view class="station-swap-view" @click="exchange">
									<view class="iconfont icon-huanyihuan i-swap text-30 " :class="changeFlag?'swap-animation':''"></view>
									<view class="iconfont icon-tuijianqiche i-bus"></view>
								</view>
								<view @click="goEndCityList('bus')"  class="bus-station station-right text-black"  :class="changeFlag?'swap-animation':''">
									<text :class="end_loc?'':'text-cf'">{{end_loc?end_loc.name:'选择目的地'}}</text>
								</view>
							</view>
							<view class="separate-line"></view>
							<view class="date-row" @click="openDate">
								<view class="date-t">
									出发日期
								</view>
								<view v-if="selectDay" class="text-20 ft-w700 absolute " style="top: 15px;">
									<text class="mr-5">{{selectDayMd?selectDayMd:''}}</text>
									<text class="">{{selectDayWeek?selectDayWeek:''}}</text>
								</view>
								<view v-else class="text-20 ft-w700 absolute " style="top: 15px;color: #999;">
									选择出发日期
								</view>
							</view>
							<view class="separate-line"></view>
							<view class="mt-5 mb-10">
								<view class="button-search" @click="searchPlan">
									<text class="text">查询</text>
								</view>
							</view>
							<view class="history-row"  v-if="historyList&&historyList.length">
								<text class="history-text" @click="goPlan(item)" v-for="(item,index) in historyList" :key="index">
									{{item.origin}}-{{item.destination}}
								</text>
								<text class="history-text" @click="clearSearchHistory">清除历史</text>
							</view>
						</view>
						
					</view>
					<view class="tab-bar">
						<view class="tab-item" @click="goOrderList">
							<view class="iconfont icon-a-ic_ic_orderforgoods1 text-20">	</view>
							<view class="mt-5 text-14">
								我的订单
							</view>
						</view>
						<view class="tab-item"  >
							<!-- <view class="iconfont icon-kefu"></view> -->
							<kefu></kefu>
							<view class="mt-5 text-14">
								联系客服
							</view>
							
						</view>
					</view>
				</view>
			</view>
			
			<view class="mb-100">
				<recommend  :hostProduct='hostProduct' :isLogin="isLogin"></recommend>
				<view class="loadingicon acea-row row-center-wrapper" v-if="hostProduct.length > 0">
					<text class="loading iconfont icon-jiazai" :hidden="hotLoading == false"></text>
					{{ hotTitle }}
				</view>
			</view>
			
		</view>
	    <uni-popup ref="bindmobile" type="bottom" background-color="#fff">
	    	 <scroll-view class="" style="height: 500px;">
	    	 	<calendar :salesDates="dateList" :start-date="selectDay" @callback="dateChange" @colseCal="colseCal">
	    	 	</calendar>
	    	 </scroll-view>
	    </uni-popup>
	</view>
</template>

<script>
import Cache from '@/utils/cache';
import { CITY_INFO ,FROM_LOC ,TO_LOC ,USER_LOCATION} from '@/config/cache'
import { getCityInfo} from '@/api/api.js';
import { getProductHot } from '@/api/store.js';
import dayjs from '@/utils/day.js'
import util from '@/utils/util.js'
import { configMap, getCustomer } from "@/utils";
import calendar from '@/components/calendar/index'
import recommend from '@/components/recommend';
import {
	mapGetters
} from "vuex";
let app = getApp();
var sysHeight = uni.getSystemInfoSync().statusBarHeight;
	import { toLogin } from '@/libs/login.js';
export default {
	data() {
		return {
			sysHeight: sysHeight, //系统导航条高度
			start_loc: '',
			end_loc: '',
			changeFlag: false,
			isInitLoc: false,
			isLocCancel: false,
			selectDay: '',
			selectDayMd: '',
			selectDayWeek: '',
			dateList: [],
			navH: '',
			opacity: 0,
			homeTop: 59,
			historyList:[],
			hostProduct: [],
			hotPage: 1,
			hotLimit: 10,
			hotScroll: true,
			hotLoading: false,
			hotTitle: '加载更多',
		};
	},
	components:{ calendar ,recommend},
	computed: configMap({recommend_switch:0},mapGetters(['isLogin','viewColor'])),
	
	onLoad(options) {
		var that = this;
		// that.navH = app.globalData.navHeight+10;
		uni.getSystemInfo({
			success: function(res) {
				console.log('res',res)
				that.navH = res.statusBarHeight * (750 / res.windowWidth) + 100;
				// that.navH = app.globalData.navHeight+10;
				console.log('that.navH',that.navH)
			}
		});
		// #ifdef APP-PLUS
		that.homeTop = (that.sysHeight + 8)*2;
		// #endif
		// #ifdef H5
		that.homeTop = 10;
		// #endif
		
		const tow = dayjs().add(1, 'day');
		this.selectDay = tow.format('YYYY-MM-DD')
		this.selectDayMd =  tow.format('MM月DD日')
		this.selectDayWeek =  util.getWeek(tow.day())
		console.log(this.selectDay,this.selectDayMd,this.selectDayWeek)
		// 设置日期
		this.initDateList()
		
	},
	
	onShow() {
		var that = this;
		this.start_loc = Cache.has(FROM_LOC)?JSON.parse(Cache.get(FROM_LOC)):''
		this.end_loc = Cache.has(TO_LOC)?JSON.parse(Cache.get(TO_LOC)):''
		console.log('start_loc',this.start_loc)
		console.log('end_loc',this.end_loc)
		// #ifdef MP-WEIXIN
		uni.getSetting({
		    success: (res) => {
		    let authSetting = res.authSetting
			
		    if (authSetting['scope.userLocation']) {
		      // 已授权
			  that.initLngLat()
		    } else {
			  that.initLngLat()
		    }
		  }
		})
		//#endif
		// #ifdef MP-ALIPAY
		uni.getSetting({
		    success: (res) => {
		    let authSetting = res.authSetting
			
		    if (authSetting['location']) {
		      // 已授权
			  that.initLngLat()
		    } else {
		       that.initLngLat()
		    }
		  }
		})
		//#endif
		
		this.historyList = uni.getStorageSync('qyxhistoryListOriginDt') ? uni.getStorageSync('qyxhistoryListOriginDt') : [];

		
	},
	onUnload() {
		Cache.clear('TO_LOC');
		this.historyList = []
		
	},
	onReady() {
		this.$nextTick(function() {
			// #ifdef MP-WEIXIN
			const menuButton = uni.getMenuButtonBoundingClientRect();
			const query = uni.createSelectorQuery();
			query
				.select('#home')
				.boundingClientRect(data => {
					this.homeTop = menuButton.top * 2 + menuButton.height - data.height;
				})
				.exec();
			// #endif
		});
		this.get_host_product();
	},
	onPageScroll : function(e) { //nvue暂不支持滚动监听，可用bindingx代替
		var that = this,
		scrollY = e.scrollTop;
		var opacity = scrollY / 200;
		opacity = opacity > 1 ? 1 : opacity;
		that.$set(that, 'opacity', opacity);
	},
	methods: {
		searchPlan(){
			console.log('start_loc',this.start_loc)
			console.log('end_loc',this.end_loc)
			if (!this.start_loc) {
				this.$util.Tips({
					title: '请选择出发城市/站点'
				})
				return false;
			}
			if (!this.end_loc) {
				this.$util.Tips({
					title: '请选择到达城市/站点'
				})
				return false;
			}
			if (!this.selectDay) {
				this.$util.Tips({
					title: '请选择出发日期'
				})
				return false;
			}
			var start_city_id = '';
			var end_city_id = '';
			var start_stop_id = '';
			var end_stop_id = '';
			if(this.start_loc.type == 1){
				start_city_id = this.start_loc.id;
			}
			if(this.start_loc.type == 2){
				start_stop_id = this.start_loc.id;
			}
			if(this.end_loc.type == 1){
				end_city_id = this.end_loc.id;
			}
			if(this.end_loc.type == 2){
				end_stop_id = this.end_loc.id;
			}
			
			var historyList = this.historyList;
			for (var r = 0; r < historyList.length; r++) {
				if(historyList[r].origin == this.start_loc.name&&historyList[r].destination == this.end_loc.name){
					historyList.splice(r, 1);
				}	
			}
			historyList.length >= 10 && historyList.splice(historyList.length - 1, historyList.length);
			historyList.unshift({
				start_city_id: start_city_id,
				start_stop_id: start_stop_id,
				end_city_id: end_city_id,
				end_stop_id: end_stop_id,
				origin: this.start_loc.name,
				destination:this.end_loc.name
			})
			
			uni.setStorageSync('qyxhistoryListOriginDt', historyList);
			
			
			uni.navigateTo({
				url: '/pages/bus/plan_list/index?date='+this.selectDay
				+'&start_city_id='+start_city_id
				+'&start_stop_id='+start_stop_id
				+'&end_city_id='+end_city_id
				+'&end_stop_id='+end_stop_id
				+'&origin='+this.start_loc.name
				+'&destination='+this.end_loc.name
			})
		},
		
		goPlan(item){
			console.log('item',item)
			 uni.navigateTo({
			 	url: '/pages/bus/plan_list/index?date='+this.selectDay
			 	+'&start_city_id='+item.start_city_id
			 	+'&start_stop_id='+item.start_stop_id
			 	+'&end_city_id='+item.end_city_id
			 	+'&end_stop_id='+item.end_stop_id
			 	+'&origin='+item.origin
			 	+'&destination='+item.destination
			 })
		},
		clearSearchHistory: function () {
		    var t = this;
		    uni.showModal({
		        title: "提示",
		        content: "清空全部历史记录？",
		        confirmColor: "#427CFF",
		        confirmText: "清空",
		        success: function (e) {
		            if (e.confirm) try {
		                uni.removeStorageSync('qyxhistoryListOriginDt'), t.historyList = [];
		            } catch (e) {
		               return this.$util.Tips({
		               	title: err
		               }); 
		            }
		        }
		    });
		},
		
		exchange(){
			if(!this.start_loc|| !this.end_loc){
				return this.$util.Tips({title: '请先选择出发地或者目的地'})
			}
			var that = this;
			this.changeFlag = true;
			let middel = this.start_loc;
		
			setTimeout(() => {
				that.changeFlag = false;
				that.start_loc = that.end_loc;
				that.end_loc = middel;
			},250)
		},
		initDateList(){
			for (var i = 0; i <60; i++) {
				this.dateList.push({
					date: dayjs((dayjs(dayjs().format('YYYY-MM-DD')).unix()+ 86400*i)*1000).format('YYYY-MM-DD')
			
				})
			}	
		},
		openDate(){
			this.$refs.bindmobile.open()
		},
		colseCal(){
			this.$refs.bindmobile.close()
		},
		dateChange:function(date){
			var that = this;
			// this.selectDay = date.startStr.dateStr;	
			console.log('this.date',date)
			
		this.selectDay =  date.startStr.dateStr
		this.selectDayMd =  dayjs(this.selectDay).format('MM月DD日')
		this.selectDayWeek =  util.getWeek(dayjs(this.selectDay).day())
		
			this.$refs.bindmobile.close()
		},
		
		goStartCityList(){
			uni.navigateTo({
				url: '/pages/bus/start_city_list/index'
			})
		},
		goEndCityList(){
			if(!this.start_loc){
				return this.$util.Tips({title: '请先选择出发地'})
			}
			var start_city_id = '';
			var start_stop_id = ''
			if(this.start_loc.type == 1){
				start_city_id = this.start_loc.id;
			}
			if(this.start_loc.type == 2){
				start_stop_id = this.start_loc.id;
			}
			uni.navigateTo({
				url: '/pages/bus/end_city_list/index?start_city_id='+start_city_id+'&start_stop_id='+start_stop_id
			})
		},
		initLngLat(){
			var that = this
			uni.getLocation({
					type: 'gcj02',
					altitude: true,
					success: function(res) {
						Cache.set(USER_LOCATION,{lng: res.longitude,lat: res.latitude,})
						getCityInfo({lng: res.longitude,lat: res.latitude,}).then(res2 => {
							that.isInitLoc = true;
				
							res2 = res2.data;
							Cache.set(CITY_INFO,res2);
							console.log('res2',res2)
							// 如果没有出发在更新
							if(!that.start_loc){
								Cache.set(FROM_LOC,res2)
								that.start_loc  = res2;
							}
							
						}).catch(err => {
		
						})
						
					},
					complete: function(res) {
					},
					fail: function(err){
						console.log('err',err)
						getCityInfo().then(res2 => {
							that.isInitLoc = true;
							res2 = res2.data;
							Cache.set(CITY_INFO,res2);
							// Cache.set(FROM_LOC,res2)
							// this.start_loc  = res2;
						
						}).catch(err => {
						
						})
						
						that.openLocSetting()
					}
				
				});
		},
		goOrderList(){
			uni.navigateTo({
				url: '/pages/users/order_list/index?status=-1'
			})
		},
		goCustomer: function() {
			let that = this;
			if (that.isLogin === false) {
				toLogin()
			} else {
				console.log('app.globalData.sys_service_data',app.globalData.sys_service_data)
				let url = `/pages/chat/customer_list/chat?mer_id=0&uid=${that.uid}`
				getCustomer(app.globalData.sys_service_data, url);
			}
		},
		
		openLocSetting(){
			if(this.isLocCancel==false){
				// #ifdef MP-WEIXIN
				uni.getSetting({
				    success: (res) => {
				    let authSetting = res.authSetting
					
				    if (authSetting['scope.userLocation']) {
				      // 已授权
				    } else {
				      uni.showModal({
				        title: '您未开启地理位置授权',
				        content: '是否前往开启位置权限',
				        success: res => {
				          if (res.confirm) {
				            uni.openSetting()
				          } else {
							this.isLocCancel = true;
						  }
				        }
				      })
				    }
				  }
				})
				//#endif
				// #ifdef MP-ALIPAY
				uni.getSetting({
				    success: (res) => {
				    let authSetting = res.authSetting
					
				    if (authSetting['location']) {
				   
				    } else {
				      uni.showModal({
				        title: '您未开启地理位置授权',
				        content: '是否前往开启位置权限',
				        success: res => {
				          if (res.confirm) {
				            uni.openSetting()
				          } else {
							  this.isLocCancel = true;
						  }
				        }
				      })
				    }
				  }
				})
				//#endif
			}	
		},
		// 后退
		returns: function() {
			uni.switchTab({
				url:'/pages/index/index'
			})
		},
		get_host_product: function () {
			let that = this;
			let num = that.hotLimit;
			if (!that.hotScroll) return;
			if (that.hotLoading) return;
			that.hotLoading = true;
			that.hotTitle = '';
			getProductHot(that.hotPage, that.hotLimit,4,2).then(function (res) {
				let list = res.data.list;
				let productList = that.$util.SplitArray(list, that.hostProduct);
				let hotScroll = list.length <= num && list.length != 0;
				that.hotScroll = hotScroll;
				that.hotLoading = false;
				that.hotTitle = !hotScroll ? '已全部加载' : '加载更多';
				that.$set(that, 'hostProduct', productList);
				that.$set(that, 'hotPage', that.hotPage + 1);
			});
		},
	},
	// 滚动到底部
	onReachBottom() {
		this.get_host_product();
	},
}
</script>

<style lang="scss">
	.bus-index{
		position: relative;
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		flex-direction: column;
		flex: 1;
		width: 100%;
		height: 100%;
		overflow-x: hidden;
		overflow-y: scroll;
	}
	.navbar {
		position: fixed;
		background-color: #fff;
		top: 0;
		left: 0;
		z-index: 99;
		width: 100%;
	}
	.head-menu-new {
		display: flex;
		align-items: center;
		height: 60rpx;
		width: 60rpx;
		// background: rgba(0, 0, 0, .25);
		border: 0.5rpx solid #cecece;
		border-radius: 50%;
		.iconfont {
			flex: 1;
			text-align: center;
			// color: #fff;
			font-size: 18px;
			box-sizing: border-box;
			&.icon-ic_leftarrow {
				border-right: 1px solid #fff;
			}
		}
	}
	.navbar-title{
		display: flex;
		// align-items: center;
		color: #000;
		font-size: 16px;
		justify-content: center;
	}
	.bus-index-bg{
		height: 190px;
		overflow: hidden;
	}
	.bus-index-search{
		background-color: #fff;
		margin: -40px 15px 15px;
		padding: 15px 15px 0 15px;
		border-radius: 5px;
		box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.05);
		position: relative;
	}
	.bus-from{
		left: 0;
		position: absolute;
		top: 15px;
		font-size: 10px;
		color: #999;
	}
	.bus-to{
		right: 0;
		position: absolute;
		top: 15px;
		font-size: 10px;
		color: #999;
	}
	.bus-index-city{
		margin-top: 10px;
		height: 60px;
		font-size: 20px;
		font-weight: 500;
		padding: 4;
		align-self: stretch;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}
	.city-block {
		flex: 1;
		font-size: 18px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		height: 44px;
		line-height: 44px;
	}

	.bus-station{
		height: 60px;
		line-height: 60px;
		font-weight: 700;
		flex: 1;
		opacity: 1;
		transition: all .25s ease-in-out;
		text-overflow: ellipsis;
		overflow: hidden;
		white-space: nowrap;
		// color: #999;
	}
	.station-left {
	    text-align: left;
	}
	.station-right {
	    text-align: right;
	}
	.station-swap-view{
		color: var(--view-theme);
		width: 30px;
		align-self: stretch;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 8px;
	}
	.i-bus{
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		font-size: 15px;
		
	}
	.date-row {
	    height: 70px;
	    display: flex;
	    flex-direction: column;
	    align-items: baseline;
	    line-height: 70px;
		position: relative;
	}
	.date-t{
		left: 0;
		font-size: 10px;
		color: #999;
		line-height: 12px;
		font-weight: normal;
		position: absolute;
		top: 15px;
	}
	.history-row {
		padding-bottom: 12px;
		line-height: 12px;
		white-space: nowrap;
		overflow-x: auto;
		overflow: -moz-scrollbars-none;
	}
	.history-text{
		color: #999;
		font-size: 12px;
		margin-right: 11px;
		
	}
	.history-text:last-child {
	    margin-right: 0;
	}
	.tab-bar {
	    background-color: #fff;
	    position: fixed;
	    left: 0;
	    right: 0;
	    bottom: 0;
	    display: flex;
	    flex-direction: row;
	    justify-content: space-around;
	    height: 57px;
	    box-shadow: 0 -3px 2px 0 rgba(0, 0, 0, .05);
		z-index: 99;
	}
	.tab-bar .tab-item {
	    margin-top: 6px;
	    display: flex;
	    flex-direction: column;
	    align-items: center;
	    color: #333;
	    font-size: 12px;
	}
	.i-swap.swap-animation {
		transition: all .25s ease-in-out;
		transform: rotate(180deg)
	}
	.station-left.swap-animation {
	    transform: translateX(100%);
	    opacity: 0
	}
	.station-right.swap-animation {
	    transform: translateX(-100%);
	    opacity: 0
	}
</style>
